package com.simon.samples.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;

public class Login implements EntryPoint {
	private LoginServiceAsync loginService = GWT.create(LoginService.class);

	@Override
	public void onModuleLoad() {
		RootPanel rootPanel = RootPanel.get();

		VerticalPanel verticalPanel = new VerticalPanel();
		rootPanel.add(verticalPanel, 10, 84);
		verticalPanel.setSize("374px", "133px");

		HorizontalPanel hpUsername = new HorizontalPanel();
		verticalPanel.add(hpUsername);

		Label lblUsername = new Label("Username:");
		hpUsername.add(lblUsername);

		final TextBox tbUsername = new TextBox();
		hpUsername.add(tbUsername);

		HorizontalPanel hpPassword = new HorizontalPanel();
		verticalPanel.add(hpPassword);

		Label lblPassword = new Label("Password");
		hpPassword.add(lblPassword);

		final PasswordTextBox tbPassword = new PasswordTextBox();
		hpPassword.add(tbPassword);
		tbPassword.setText("");

		Button btnLogin = new Button("Login");
		btnLogin.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				btnLoginOnClick(tbUsername.getValue(),tbPassword.getValue());
			}
		});
		verticalPanel.add(btnLogin);
	}
	public void btnLoginOnClick(String username,String password) {

		// Initialize the service proxy.
		if (loginService == null) {
			loginService = GWT.create(LoginService.class);
		}

		// Set up the callback object.
		AsyncCallback<SessionID> callback = new AsyncCallback<SessionID>() {
			public void onFailure(Throwable caught) {
				// If the stock code is in the list of delisted codes, display an error message.
				String details = caught.getMessage();
				if (caught instanceof IncorrectUserOrPassword) {
					details = "Incorrect username or password("+((IncorrectUserOrPassword)caught).getUsername()+","+((IncorrectUserOrPassword)caught).getPassword()+")";
				}
				Window.alert(details);
			}

			public void onSuccess(SessionID result) {
				Window.alert("Session ID: "+result.getIdString()+result.getId());
			}
		};
		loginService.login(username, password, callback);
	}
}
